package com.youhui.weixin.weixin;

import com.youhui.weixin.common.MythConfig;
import com.youhui.weixin.common.exception.MythException;
import com.youhui.weixin.dao.GoodsDao;
import com.youhui.weixin.domain.Goods;
import com.youhui.weixin.utils.weixin.WXMenuUtils;
import com.youhui.weixin.utils.weixin.WXMessagesUtils;

import com.youhui.weixin.weixin.domain.News;
import com.youhui.weixin.weixin.service.MessageService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static com.youhui.weixin.utils.weixin.WXConfig.*;
/**
 * Created by https://github.com/kuangcp on 17-9-26  下午5:14
 * 主要公众号的连接接口 服务器校验，以及消息的收发
 */
@RestController
@Log4j
public class MainController {


    @Autowired
    WXMenuUtils menuUtils;
    @Autowired
    MessageService messageService;



    @RequestMapping("/createMenu")
    public String createMenu(){
        try {
            menuUtils.createMenu();
        } catch (MythException e) {
            return "{\"result\":\""+e.getMessage()+"\"}";
        }
        return "{\"result\":\"success\"}";
    }
    @GetMapping("/wx")
    public String check(String signature, String timestamp, String nonce, String echostr){
        log.info("一次来自微信服务器校验请求："+signature+"-"+timestamp+"-"+echostr);
        if(messageService.sort(signature, timestamp, nonce)){
            return echostr;
        }else {
            return null;
        }
    }


    // 对象里面的属性如果和参数列表中某参数同名会报错，所以要 避免 /wx/user
    @PostMapping("/wx")
    public String receiveMsg(HttpServletRequest request) {
        // 读取请求中的参数
        String fromUserName = null;
        String toUserName = null;
        String msgType = null;
        String content = null;
        String resultMessage = null;
        Map<String, String> params = null;

        try {
            params = WXMessagesUtils.xmlToMap(request);
            msgType = params.get("MsgType");
            content = params.get("Content");
            toUserName = params.get("ToUserName");
            fromUserName = params.get("FromUserName");
            log.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 自动回复：文本类型的处理
        // TODO 可以优化为 redis存储对应的键值对来自定义回复消息
        if (MESSAGE_TEXT.equals(msgType)) {
            if (content != null && (content.contains("打开\uD83D\uDC49手淘\uD83D\uDC48") || content.contains("打开\uD83D\uDC49天猫APP\uD83D\uDC48"))) {
                String result = messageService.search(content);
                if("0".equals(result)){
                    result = "优惠券已领完，下次早点来哦。\n<a href=\"wx.jjyouhuigo.com/searchs\">点击查看更多优惠</a>";
                }else{
                    result = "<a href=\" "+result+" \">点击领取优惠券</a>";
                }
                resultMessage = WXMessagesUtils.loadText(toUserName, fromUserName, result);
            }else{
                content = "%"+content+"%";
                Page<Goods> goodsList = messageService.searchSimple(content);
                List<News> results = new ArrayList<>();
                for(Goods goods : goodsList){
                    News news = new News();
                    news.setPicUrl(goods.getImage());
                    news.setUrl("http://wx.jjyouhuigo.com/good/"+goods.getGoodsId());
                    String price = goods.getPrice()-goods.getDiscount()+"00";
                    System.out.println(price);
                    price = price.split("\\.")[0]+"."+price.split("\\.")[1].substring(0,2);
                    news.setTitle("券后￥"+price+"|"+goods.getName().substring(0,8)+"...");
                    news.setDescription(goods.getPrice()+"");
                    results.add(news);
                }
                News news = new News();
                news.setUrl("http://wx.jjyouhuigo.com/searchs");
                news.setTitle("           >>>>搜索更多优惠券<<<<");
                results.add(news);
                resultMessage = WXMessagesUtils.loadNews(toUserName, fromUserName, results);
            }

        }
        // 响应接收到的事件消息
        if (MESSAGE_EVENT.equals(msgType)){
            String eventType = params.get("Event");
            if (EVENT_SUBSCRIBE.equals(eventType)){
                resultMessage = WXMessagesUtils.loadText(toUserName, fromUserName, "欢迎来到券你生活！\n" +
                        "你的生活，因券出彩!\n" +
                        "你的网购，因券优惠！\n" +
                        "我们致力于为大家提供网购优惠券，\n" +
                        "每日万件商品折扣优惠券，免费领取直接省钱！\n" +
                        "现在因券省下的这笔钱都够你毕业后创业的启动资金啦！\n" +
                        "还在等什么，come on! \n");
            }else if (EVENT_CLICK.equals(eventType)){
                String key = params.get("EventKey").toLowerCase();
                if (key.equals("使用指南")) {
                    resultMessage = WXMessagesUtils.loadText(toUserName, fromUserName, "天猫券只要复制对应的淘口令， 然后打开淘宝就会自动弹出对应的券。\n" +
                            "腾讯券是腾讯投资的电商平台， 可以直接在微信中领券下单购买商品。\n" +
                            "从淘宝中分享出的淘口令可以直接发送到公众号进行查询是否有优惠券\n" +
                            "或者直接发送任意字即可进行搜索 ");
                }
            }else if (EVENT_VIEW.equals(eventType)){
                String key = params.get("EventKey");
                resultMessage = WXMessagesUtils.loadText(toUserName, fromUserName, key);
            }else if (EVENT_SCANCODE.equals(eventType)){
                String key = params.get("EventKey");
                resultMessage = WXMessagesUtils.loadText(toUserName, fromUserName, key);
            }
        }else if (MESSAGE_LOCATION.equals(msgType)){
            String label = params.get("Label");
            resultMessage = WXMessagesUtils.loadText(toUserName, fromUserName, label);
        }
        log.debug(resultMessage);
        return resultMessage;
    }
}
